package net.zjitc.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.zjitc.security.model.AuthenticationBean;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

//@Component

/**
 * 自定义的登录处理
 */
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        //处理登录的json数据
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)||
                request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE )){
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authenticationToken = null;
            try (InputStream is = request.getInputStream()){
                AuthenticationBean authenticationBean = mapper.readValue(is, AuthenticationBean.class);
                authenticationToken =  new UsernamePasswordAuthenticationToken(authenticationBean.getUsername(),authenticationBean.getPassword());
            }catch (Exception e){
                e.printStackTrace();
                authenticationToken = new UsernamePasswordAuthenticationToken("","");
            }finally {

                setDetails(request,authenticationToken);
                return super.getAuthenticationManager().authenticate(authenticationToken);
            }
        }else {
            return super.attemptAuthentication(request, response);
        }
    }
}
